package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Employee;
import com.itheima.bean.Employee2;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.exception.CustomException;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Tang
 * @date 2023/2/20
 */
@Slf4j
@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        if (password == null) {
            return R.error("密码不能为空！");
        }
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(wrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("该用户不存在！");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!pwd.equals(emp.getPassword())){
            return R.error("用户名密码不匹配！");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果 0代表禁用 1正常
        if (emp.getStatus() == 0) {
            return R.error("该员工已被禁用！");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        session.setAttribute("employeeId", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        //1.清理session中的id
        session.invalidate();

        //2.返回结果
        return R.success("退出成功！");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee2 employee) {

        if (StringUtils.isNotEmpty(employee.getRePassword()) && StringUtils.isNotEmpty(employee.getPassword())) {
            setPassword(employee);
            return R.success("密码修改成功");
        }
        log.info("新增员工,员工信息:{}", employee.toString());
        //设置初始密码w123456,需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("w123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //获取当前登录用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        employeeService.save((Employee)employee);
        return R.success("新增员工成功");
    }

    @PostMapping("/updatePassword")
    public R<String> setPassword(@RequestBody Employee2 employee) {
        log.info("参数:{}",employee);
        // 根据线程局部变量获取登录人id

        Long currentId = BaseContext.getCurrentId();
        log.info("修改密码");

        // 判断是否管理员
        LambdaQueryWrapper<Employee> elqw = new LambdaQueryWrapper<>();
        elqw.eq(Employee :: getId,currentId).eq(Employee :: getName,"管理员");
        int count = employeeService.count(elqw);
        if(count > 0) {
            // 判断账号是否存在;即username是否存在,存在就修改密码,不存在提示账号错误
            LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
            String username = employee.getUsername();
            qw.eq(username!=null,Employee :: getUsername, username);
            Employee emp = employeeService.getOne(qw);
            if(emp == null){
                throw new CustomException("该账号不存在");
            }
            //管理员修改新的密码
            String newPwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
            emp.setPassword(newPwd);
            employeeService.updateById(emp);

        }else{
            //员工修改密码
            LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
            //获取当前登录id,查询是否在数据库存在
            qw.eq(Employee :: getId, BaseContext.getCurrentId());
            Employee user = employeeService.getOne(qw);
            if(user == null) throw new CustomException ("用户名不存在");

            //获取前端的原始密码,到数据库密码进行比较
            String rePwd = DigestUtils.md5DigestAsHex(employee.getRePassword().getBytes());
            if(! user.getPassword().equals(rePwd)){
                throw new CustomException("原密码错误");
            }
            //获取员工的新密码,到数据库进行比较原密码
            String newPassword = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
            if(user.getPassword().equals(newPassword)) throw new CustomException("新密码与原密码一致,设置失败!");

            //员工修改新密码
            user.setPassword(newPassword);
            //调用更新方法,进行保存密码
            employeeService.updateById(user);

            //员工本人修改,需要判断是否与当前登录的id账号一样,不一样抛出权限不足;

            //账号一样,需要输入账号跟原密码,新密码,获取当前员工id,查询数据库,匹配账号跟原密码一样时,新密码替换原密码,保存成功提示修改成功
        }
        return R.success("修改密码成功!");
    }
//    @PostMapping
//    public R<String> addEmployee(@RequestBody Employee employee, HttpSession session) {
//        //优化：新增员工之前，判断该用户名是否已经存在数据库中
//        /*LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Employee::getUsername, employee.getUsername());
//        Employee one = employeeService.getOne(wrapper);
//        if (one != null) {
//            //return R.error("该用户名【"+employee.getUsername()+"】已存在！");
//            throw new CustomException("该用户名【"+employee.getUsername()+"】已存在！");
//        }*/
//
//        //1.补齐字段
//        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        //优化：公共字段自动填充
//        /*employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        Long employeeId = (Long) session.getAttribute("employeeId");
//        employee.setCreateUser(employeeId);
//        employee.setUpdateUser(employeeId);*/
//
//        //2.调用service新增方法
//        boolean flag = employeeService.save(employee);
//
//        //3.返回结果
//        return flag ? R.success("新增成功！") : R.error("新增失败！");
//    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize, String name){
        //0.添加分页拦截器
        //1.设置分页对象 Page对象
        Page<Employee> employeePage = new Page<>(page, pageSize);

        //2.设置查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Employee::getName, name);

        //3.调用service的分页查询方法
        employeeService.page(employeePage, wrapper);

        //4.返回结果
        return R.success(employeePage);
    }

    /**
     * 员工启用|禁用  + 员工编辑
     * @param employee
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session) {
        log.info("EmployeeController 的线程id:{}",Thread.currentThread().getId());
        //编辑员工：优化
        //在更新员工信息之前，先查询员工表，判断当前修改的用户名是否存在（根据前端传递的用户名查询，注意：要排除它自生数据）
        /*if (employee.getUsername() != null) {  //如果有用户名，说明在做编辑操作
            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Employee::getUsername, employee.getUsername());
            wrapper.ne(Employee::getId, employee.getId());
            int count = employeeService.count(wrapper);
            if (count > 0) {
                throw new CustomException("该用户名【"+employee.getUsername()+"】已存在！");
            }
        }*/

        //1.补齐更新时间和更新人
        //优化：公共字段自动填充
        /*employee.setUpdateTime(LocalDateTime.now());
        Long employeeId = (Long) session.getAttribute("employeeId");
        employee.setUpdateUser(employeeId);*/

        //2.调用service更新方法根据id更新
        boolean flag = employeeService.updateById(employee);

        //3.返回结果
        return flag ? R.success("修改成功！") : R.error("修改失败！");
    }

    /**
     * 根据员工id查询员工信息（回显）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        //1.调用service的查询方法（根据id查询）
        Employee employee = employeeService.getById(id);
        //2.返回结果
        return R.success(employee);
    }
}
